/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.ugd.controller;

import edu.ugd.domain.EncodingForm;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

/**
 * @author User
 */
@Controller
@SessionAttributes({"encodingForm"})
public class Base64Controller extends Base {

    @RequestMapping(value = "/base64.htm", method = RequestMethod.GET)
    public String doBase64(
            HttpServletRequest req,
            ModelMap model) {
        HttpSession session = req.getSession();
        session.setAttribute("encodingForm", new EncodingForm());
        model.put("encodingForm", new EncodingForm());
        model.put("encodings", getEncodings());
        return "base64";
    }

    @RequestMapping(value = "/base64.htm", method = RequestMethod.POST)
    public String submitBase64(
            HttpServletRequest request,
            HttpServletResponse response,
            @ModelAttribute("encodingForm") EncodingForm encodingForm,
            @RequestParam String action,
            ModelMap model) throws UnsupportedEncodingException {
        if (encodingForm != null) {
            String userInput = encodingForm.getUserInput();
            if (userInput != null && !userInput.equals("")) {
                if (action.equals("encode")) {
                    byte[] encodedBytes = Base64.encodeBase64(encodingForm.getUserInput().getBytes(Charset.forName(encodingForm.getEncoding())));
                    encodingForm.setGeneratedOutput(new String(encodedBytes));
                } else {
                    byte[] decodedBytes = Base64.decodeBase64(encodingForm.getUserInput().getBytes(Charset.forName(encodingForm.getEncoding())));
                    encodingForm.setGeneratedOutput(new String(decodedBytes,encodingForm.getEncoding()));
                }
            }
        }
        model.put("encodings", getEncodings());
        return "base64";
    }
}
